<!-- LoginView.vue -->
<template>
  <div class="login-container">
    <!-- 登录卡片 -->
    <el-card class="login-card" shadow="never">
      <template #header>
        <h2 class="login-title">登录</h2>
      </template>

      <!-- 登录表单 -->
      <el-form
        :model="formData"
        :rules="rules"
        ref="loginFormRef"
        class="login-form"
        @submit.prevent="onSubmit"
      >
        <!-- 账号 -->
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            clearable
            show-password
          />
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item label="验证码" prop="captcha">
          <!-- 输入框 + 验证码图片 -->
          <div style="display: flex; align-items: center; gap: 10px">
            <el-input
              v-model="formData.captcha"
              placeholder="请输入验证码"
              style="width: 160px"
              @keyup.enter="onSubmit"
            />
            <!-- 验证码显示区域 -->
            <div
              class="captcha-img"
              @click="refreshCaptcha"
              :style="{ cursor: 'pointer', userSelect: 'none' }"
            >
              {{ captcha }}
            </div>
          </div>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            native-type="submit"
            :loading="loading"
            class="submit-btn"
          >
            {{ loading ? "登录中..." : "登 录" }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 其他链接 -->
      <div class="login-links">
        <el-link type="primary" @click="gotoForgetPassword">忘记密码？</el-link>
        <el-link type="success" @click="gotoRegister">没有账号？去注册</el-link>
      </div>
    </el-card>
  </div>
  <app-footer></app-footer>
</template>

<script setup>
import "@/assets/styles/login-common.css"; // 局部导入样式文件
import { ref, reactive, onMounted, inject } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import AppFooter from "@/components/Footer/Footer.vue";
import { login } from "@/api/user";
import { loginUser } from "@/stores/user";

// import { defineEmits } from 'vue'
// const emit = defineEmits(['to-register', 'to-forget', 'close'])

// 获取表单实例
const loginFormRef = ref(null);

// 表单数据（增加 captcha 字段）
const formData = reactive({
  username: "",
  password: "",
  captcha: "", // 用户输入的验证码
});

// 当前显示的验证码（4位随机字符）
const captcha = ref("");

// 生成随机验证码（调用API接口）
const generateCaptcha = async () => {
  try {
    const response = await fetch("/api/captcha", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();

    if (result.code === 200) {
      console.log("api获得的验证码：", result.data);
      return result.data;
    } else {
      throw new Error(result.msg || "获取验证码失败");
    }
  } catch (error) {
    console.error("获取验证码失败:", error);
    // 如果API调用失败，使用本地生成的验证码作为备用
    const chars = "ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789";
    let result = "";
    for (let i = 0; i < 4; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  }
};

// 刷新验证码
const refreshCaptcha = async () => {
  captcha.value = await generateCaptcha();
};

// 页面加载时生成初始验证码
onMounted(() => {
  refreshCaptcha();
});

// 表单验证规则（增加 captcha 校验）
const rules = reactive({
  username: [
    { required: true, message: "请输入用户名或邮箱", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于 6 位", trigger: "blur" },
  ],
  captcha: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          return callback(new Error("请输入验证码"));
        }
        // ✅ 这里可以设置忽略大小写比对
        if (value.toLowerCase() !== captcha.value.toLowerCase()) {
          callback(new Error("验证码错误，请重新输入"));
        } else {
          callback(); // 验证通过
        }
      },
      trigger: "blur",
    },
  ],
});

// 加载状态
const loading = ref(false);

// 使用路由
const router = useRouter();
// 获取用户状态
const user = inject("user");

// 登录提交
const onSubmit = () => {
  loginFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error("请检查表单输入");
      return false;
    }

    // 验证通过，开始登录请求
    loading.value = true;
    console.log("登录请求:", formData);

    try {
      // 调用真实的登录API
      const loginData = {
        username: formData.username,
        password: formData.password,
      };

      const userData = await login(loginData);

      // 登录成功，更新用户状态
      loginUser(userData);

      // 更新注入的用户状态（兼容现有代码）
      if (user.value) {
        user.value.isLoggedIn = true;
        user.value.name =
          userData.nickname || userData.username || formData.username;
        user.value.avatar = userData.avatar
          ? `http://192.168.199.231:9000/fznostalgia/user/${userData.avatar}`
          : new URL("@/assets/images/avatar/cha1.png", import.meta.url).href;
      }

      ElMessage.success(
        `欢迎回来，${userData.nickname || formData.username}！`
      );
      router.push("/");
    } catch (error) {
      ElMessage.error("登录失败: " + error.message);
    } finally {
      loading.value = false;
    }
  });
};

const gotoForgetPassword = () => router.push("/forget");
const gotoRegister = () => router.push("/register");
</script>

<style scoped>
/* === 保持原有样式不变 === */
/* （你的 login-common.css 已导入，这里无需重复写） */

/* === 验证码样式 === */
.captcha-img {
  width: 100px;
  height: 40px;
  background: #f0f2f5;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 18px;
  font-weight: bold;
  color: #d4380d;
  display: flex;
  justify-content: center;
  align-items: center;
  letter-spacing: 5px;
  text-transform: uppercase;
  /* 可选：加点干扰线或背景纹理 */
  background-image: linear-gradient(transparent, #e0e0e0 50%, transparent),
    linear-gradient(90deg, transparent, #f9f9f9, transparent);
  background-size: 100% 2px, 100% 100%;
}

/* 响应式优化 */
@media (max-width: 480px) {
  .captcha-img {
    width: 80px;
    font-size: 16px;
  }
  .el-input {
    width: 140px !important;
  }
}
</style>
